package com.brozers.islamdini;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.DTDHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;










import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MainActivity extends Activity implements android.view.View.OnClickListener{
	
	
	String prayertimes;
	SitesList sitesList = null;
	ProgressDialog dialog;
	Thread downloadThread;
	
	Calendar c;
	int minute;
	int hour;
	String day;
	String month;
	String year;
	
	Boolean changeCity;
	
	public static final int MENU_ABOUT = 1000;
	public static final int MENU_FAQ   = 1001;
	
	TextView setTextCity;
	
	TextView setTextDate;
	
	TextView textView1;
	TextView textView2;
	TextView textView3;
	TextView textView4;
	TextView textView5;
	TextView textView6;
	
	TextView textView11;
	TextView textView22;
	TextView textView33;
	TextView textView44;
	TextView textView55;
	TextView textView66;
	 
	TableRow tablerow1 ;
	TableRow tablerow2 ;
	TableRow tablerow3 ;
	TableRow tablerow4 ;
	TableRow tablerow5 ;
	TableRow tablerow6 ;
	
	ImageButton share_button;
	ImageButton settings_button;
	ImageButton info_button;
	ImageButton map_button;
	 
	TableLayout tableLayout;
	
	static String cityId;
	static Boolean updateData;
	String [] cityID;
	String [] cityName;
	String[] numMonth;
	String [] cityName_kz;
	String[] numMonth_kz;
	String [] cityName_ru;
	String[] numMonth_ru;
	String [] cityName_en;
	String[] numMonth_en;
	
	String [] imsak;
	String [] kun;
	String [] besin;
	String [] ekindi;
	String [] sham;
	String [] kuptan;
	
	String  imsak_;
	String  kun_;
	String  besin_;
	String  ekindi_;
	String  sham_;
	String  kuptan_;
	
	String title [];
	String context [];
	String yes[];
	
	String title_;
	String context_;
	String yes_;
	
	private TimeDataSource datasource;
	
	
	MyParser parse;
	LinearLayout table1;
	
	List<Time> values;
	
	static SharedPreferences settings;
	static SharedPreferences.Editor editor;
	static int Language;
	
	static Boolean firstTime;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		datasource = new TimeDataSource(this);
	    datasource.open();
	   
	   
		 
		cityID = getResources().getStringArray(R.array.id);
		cityName_kz = getResources().getStringArray(R.array.cityName);
		numMonth_kz = getResources().getStringArray(R.array.month);
		
		cityName_ru = getResources().getStringArray(R.array.cityName_ru);
		numMonth_ru = getResources().getStringArray(R.array.month_ru);
		
		cityName_en = getResources().getStringArray(R.array.cityName_en);
		numMonth_en = getResources().getStringArray(R.array.month_en);
		
		imsak = getResources().getStringArray(R.array.imsak);
		kun =  getResources().getStringArray(R.array.kun);
		besin =  getResources().getStringArray(R.array.besin);
		ekindi =  getResources().getStringArray(R.array.ekindi);
		sham =  getResources().getStringArray(R.array.sham);
		kuptan =  getResources().getStringArray(R.array.kuptan);
		
		title =  getResources().getStringArray(R.array.title);
		context =  getResources().getStringArray(R.array.context);
		yes =  getResources().getStringArray(R.array.yes);
		
		setTextCity = (TextView) findViewById(R.id.cityName);
		setTextDate = (TextView) findViewById(R.id.date);
		
		
	    
		
		
		settings =  PreferenceManager.getDefaultSharedPreferences(this);
		
		if(!settings.getBoolean("city", false)){
			 cityId ="8408";
			 Language =1;
			 settings =  PreferenceManager.getDefaultSharedPreferences(this);
			 editor = settings.edit();
			 editor.putString("cityID", cityId);
			 editor.putInt("Language",Language);
			 editor.putBoolean("city", true);
			 editor.commit();
			}
		
		settings =  PreferenceManager.getDefaultSharedPreferences(this);
		cityId = settings.getString("cityID", "");
		
		settings =  PreferenceManager.getDefaultSharedPreferences(this);
		Language = settings.getInt("Language", 0);
		
		
		share_button = (ImageButton) findViewById(R.id.share);
		settings_button = (ImageButton) findViewById(R.id.setti);
		info_button = (ImageButton) findViewById(R.id.inf);
		map_button = (ImageButton) findViewById(R.id.maping);
		
		share_button.setOnClickListener(this);
		settings_button.setOnClickListener(this);
		info_button.setOnClickListener(this);
		map_button.setOnClickListener(this);
	   
	    
	    textView1= (TextView) findViewById(R.id.imsak);
		textView2= (TextView) findViewById(R.id.kun);
		textView3= (TextView) findViewById(R.id.besin);
		textView4= (TextView) findViewById(R.id.ekidni);
		textView5= (TextView) findViewById(R.id.sham);
		textView6= (TextView) findViewById(R.id.kuptan);
		
		textView11= (TextView) findViewById(R.id.imsak_lang);
		textView22= (TextView) findViewById(R.id.kun_lang);
		textView33= (TextView) findViewById(R.id.besin_lang);
		textView44= (TextView) findViewById(R.id.ekidni_lang);
		textView55= (TextView) findViewById(R.id.sham_lang);
		textView66= (TextView) findViewById(R.id.kuptan_lang);
		 
		tablerow1 = (TableRow) findViewById(R.id.imsakb);
		tablerow2 = (TableRow)findViewById(R.id.kunb);
		tablerow3 = (TableRow)findViewById(R.id.besinb);
		tablerow4 = (TableRow)findViewById(R.id.ekindib);
		tablerow5 = (TableRow)findViewById(R.id.shamb);
		tablerow6 = (TableRow)findViewById(R.id.kuptanb);
		
		tableLayout = (TableLayout) findViewById(R.id.tableLayout);
		
	
		
		
	}
	public void setLanguage(Boolean dup){
		if(!dup){
		switch (Language) {
		case 1:
			cityName =cityName_kz;
			numMonth = numMonth_kz;
			imsak_ = imsak[0];
			kun_ = kun[0];
			besin_ = besin[0];
			ekindi_ = ekindi[0];
			sham_ = sham[0];
			kuptan_ = kuptan[0];
			title_ = title[0];
			context_ = context[0];
			yes_ = yes[0];
			
			
			break;
		case 2:
			cityName =cityName_ru;
			numMonth = numMonth_ru;
			imsak_ = imsak[1];
			kun_ = kun[1];
			besin_ = besin[1];
			ekindi_ = ekindi[1];
			sham_ = sham[1];
			kuptan_ = kuptan[1];
			title_ = title[1];
			context_ = context[1];
			yes_ = yes[1];
			
			
			break;
		case 3:
			cityName =cityName_en;
			numMonth = numMonth_en;
			imsak_ = imsak[2];
			kun_ = kun[2];
			besin_ = besin[2];
			ekindi_ = ekindi[2];
			sham_ = sham[2];
			kuptan_ = kuptan[2];
			title_ = title[2];
			context_ = context[2];
			yes_ = yes[2];
			
			break;

		default:
			break;
			}
		}
	}
	public void setParseByID(Boolean b){
		Boolean error;
		error = false;
		 c=Calendar.getInstance();
		 minute = c.get(Calendar.MINUTE);
		 hour = c.get(Calendar.HOUR_OF_DAY);
		 day = Integer.toString(c.get(Calendar.DAY_OF_MONTH));
		 month = Integer.toString(c.get(Calendar.MONTH)+1);
		 year = Integer.toString(c.get(Calendar.YEAR));
		 
		setTextDate.setText(day + " " + numMonth[Integer.parseInt(month)-1] + " " + year);
		 for(int i=0;i<cityID.length;i++){
				if(cityId.equals(cityID[i])){
					setTextCity.setText(cityName[i]);
					
				}
				
			}
		 
	   if(!settings.getBoolean(cityId, false)){
			
			if(isNetworkAvailable()){
	    	 	parse = new MyParser(true);
	    	 	parse.execute(null);
	    	 	settings =  PreferenceManager.getDefaultSharedPreferences(this);
	    	 	editor = settings.edit();
	    	 	editor.putBoolean(cityId, true);
	    	 	editor.commit();
	    
	     }
			
			else {
				if(tableLayout.getVisibility() == View.VISIBLE){
				tableLayout.setVisibility(View.INVISIBLE);
				error = true;
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						this);
		 			alertDialogBuilder.setTitle(title_);
		 			alertDialogBuilder
						.setMessage(context_)
						.setCancelable(false)
						.setPositiveButton(yes_,new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								MainActivity.this.finish();
							}
						  });
						
						AlertDialog alertDialog = alertDialogBuilder.create();
						alertDialog.show();
				}
			}
		}
		else{
		if(!error){
			if(tableLayout.getVisibility() == View.INVISIBLE){
				tableLayout.setVisibility(View.VISIBLE);
			}
			setParse();
		}
		 if(!updateData && !b){
			 if(isNetworkAvailable()){
				 	settings =  PreferenceManager.getDefaultSharedPreferences(this);
				 	editor = settings.edit();
				 	for(int i=0;i<cityID.length;i++){
			        editor.putBoolean(cityID[i], false);
				 	}
			        editor.commit();
				 	
			        
			        if(!settings.getBoolean(cityId, false)){
			        			parse = new MyParser(false);
			    	    	 	parse.execute(null);
			    	    	 	settings =  PreferenceManager.getDefaultSharedPreferences(this);
			    	    	 	editor = settings.edit();
			    	    	 	editor.putBoolean(cityId, true);
			    	    	 	editor.commit();
			    	    	 	updateData = true;
			    	    
			    	  }
			    	}
			 else {
				 if(tableLayout.getVisibility() == View.VISIBLE){
						tableLayout.setVisibility(View.INVISIBLE);
						}
				 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							this);
			 			alertDialogBuilder.setTitle(title_);
			 			alertDialogBuilder
							.setMessage(context_)
							.setCancelable(false)
							.setPositiveButton(yes_,new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									MainActivity.this.finish();
								}
							  });
							AlertDialog alertDialog = alertDialogBuilder.create();
							alertDialog.show();
			 }
		 }
		}
	}
	public void getParse(String id){
						try {
					
					SAXParserFactory spf = SAXParserFactory.newInstance();
					SAXParser sp = spf.newSAXParser();
					XMLReader xr = sp.getXMLReader();

					URL sourceUrl = new URL(
							"http://namazvakti.com/XML.php?cityID="+id);

					MyXMLHandler myXMLHandler = new MyXMLHandler();
					xr.setContentHandler(myXMLHandler);
					xr.parse(new InputSource(sourceUrl.openStream()));
					
					sitesList = MyXMLHandler.sitesList;
					for(int i=0;i<sitesList.getPrayertimes().size();i++){
			    	datasource.createTime( cityId,sitesList.getPrayertimes().get(i),sitesList.getDayofyear().get(i),
			    			sitesList.getDay().get(i),
			    			sitesList.getMonth().get(i));
			    	}
				} catch (Exception e) {
					System.out.println("XML Pasing Excpetion = " + e);
				}
		
		}
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
	@Override
		  protected void onResume() {
		    datasource.open();
		    settings =  PreferenceManager.getDefaultSharedPreferences(this);
		    cityId = settings.getString("cityID", "");
		    Language = settings.getInt("Language", 0);
		    setLanguage(false);
			setParseByID(false);
		    super.onResume();
		  }

		  @Override
		  protected void onPause() {
		    datasource.close();
		    super.onPause();
		  }
		  public void deleteParse(){
				values = datasource.getAllTime();
				for(int i=0;i<values.size();i++){
				datasource.deleteTime(values.get(i));
				}
		  }
		 		@Override
		public void onClick(View arg0) {
		 			switch (arg0.getId()) {
					case R.id.share:
						Intent intent = new Intent(android.content.Intent.ACTION_SEND);
						intent.setType("text/plain");
						intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
						    startActivity(Intent.createChooser(intent, "Бөлісу"));
						break;
					case R.id.setti:
						startActivity(new Intent(this, Settings.class));
						break;
						
					case R.id.inf:
						startActivity(new Intent(this, Info.class));
						break;
					case R.id.maping:
						startActivity(new Intent(this, Map.class));
						break;

					default:
						break;
					}
			
			
		}
		class  MyParser extends AsyncTask<Void, Void, Void> {
			
			Boolean changeCity;
			public MyParser(Boolean changeCity) {
				this.changeCity = changeCity;
			}

			@Override
		        protected void onPostExecute(Void result) {
					setParse();
				  dialog.cancel();
		           }

		        @Override
		        protected void onPreExecute() {
		            dialog = ProgressDialog.show(MainActivity.this,
		                    "Күте тұрыңыз", "Жүктелуде....");
		            dialog.setCancelable(false);
		            super.onPreExecute();
		        }
			@Override
			protected Void doInBackground(Void... params) {
				if(!changeCity){
					deleteParse();
				}
				changeCity = true;
				getParse(cityId);
				return null;
			}
		}
		 private void setParse()
		  {
			 values = datasource.getAllTime();
			   if(values.size()>0){
				  changeCity = true;
				  updateData = true;
					 
					 for(int i=0;i<values.size();i++){
					    	
						 if(values.get(i).getMonth().equals(month) && values.get(i).getDay().equals(day) && cityId.equals( values.get(i).getCityId())){
					    		prayertimes = values.get(i).getPrayertimes();
					    		 changeCity = false;
					    	}
						 if(Integer.parseInt(values.get(i).getMonth()) != Integer.parseInt(month)){
							 updateData = false;
						 }
						}
					 if(!changeCity){
					    StringTokenizer stringTokenizer = new StringTokenizer(prayertimes);
					    
					    	String imsak = stringTokenizer.nextToken();
					    				   stringTokenizer.nextToken();
					    	String kun   = stringTokenizer.nextToken();
					    				   stringTokenizer.nextToken();
					    	               stringTokenizer.nextToken();
					    	String besin = stringTokenizer.nextToken(); 
					    	String ekindi= stringTokenizer.nextToken();
					    				   stringTokenizer.nextToken();
					    				   stringTokenizer.nextToken();
					    	String sham =  stringTokenizer.nextToken();
					    				   stringTokenizer.nextToken();
					    	String kuptan= stringTokenizer.nextToken();
					    	stringTokenizer.nextElement();
					    		
					            textView1.setText(imsak);
						    	textView2.setText(kun);
						    	textView3.setText(besin);
						    	textView4.setText(ekindi);
						    	textView5.setText(sham);
						    	textView6.setText(kuptan);
						    	
						    	textView11.setText(imsak_);
						    	textView22.setText(kun_);
						    	textView33.setText(besin_);
						    	textView44.setText(ekindi_);
						    	textView55.setText(sham_);
						    	textView66.setText(kuptan_);
						  
						StringTokenizer stringTokenizerImsak = new StringTokenizer(imsak, ":");
						int imsakHour = Integer.parseInt(stringTokenizerImsak.nextToken());
						int imsakMinute = Integer.parseInt(stringTokenizerImsak.nextToken());
						
						StringTokenizer stringTokenizerKun = new StringTokenizer(kun, ":");
						int kunHour = Integer.parseInt(stringTokenizerKun.nextToken());
						int kunMinute = Integer.parseInt(stringTokenizerKun.nextToken());
						
						StringTokenizer stringTokenizerBesin = new StringTokenizer(besin, ":");
						int besinHour = Integer.parseInt(stringTokenizerBesin.nextToken());
						int besinMinute = Integer.parseInt(stringTokenizerBesin.nextToken());
						
						StringTokenizer stringTokenizerEkindi = new StringTokenizer(ekindi, ":");
						int ekindiHour = Integer.parseInt(stringTokenizerEkindi.nextToken());
						int ekindiMinute = Integer.parseInt(stringTokenizerEkindi.nextToken());
						
						StringTokenizer stringTokenizerSham = new StringTokenizer(sham, ":");
						int shamHour = Integer.parseInt(stringTokenizerSham.nextToken());
						int shamMinute = Integer.parseInt(stringTokenizerSham.nextToken());
						
						StringTokenizer stringTokenizerKuptan = new StringTokenizer(kuptan, ":");
						int kuptanHour = Integer.parseInt(stringTokenizerKuptan.nextToken());
						int kuptanMinute = Integer.parseInt(stringTokenizerKuptan.nextToken());
						
						if(hour*60+ minute >= imsakHour*60+imsakMinute && hour*60+minute < kunHour*60+kunMinute){
							tablerow1.setBackgroundDrawable(getResources().getDrawable(R.drawable.namaz_line));
							
						}
						else if(hour*60+minute >= kunHour*60+kunMinute && hour*60+minute < besinHour*60+besinMinute){
							tablerow2.setBackgroundDrawable(getResources().getDrawable(R.drawable.namaz_line));
							
						}
						else if(hour*60+minute >= besinHour*60+besinMinute && hour*60 +minute < ekindiHour*60+ekindiMinute){
							tablerow3.setBackgroundDrawable(getResources().getDrawable(R.drawable.namaz_line));
						}
						else if(hour*60+minute>=ekindiHour*60+ekindiMinute && hour*60+minute < shamHour*60+shamMinute ){
							tablerow4.setBackgroundDrawable(getResources().getDrawable(R.drawable.namaz_line));
							}
						else if(hour*60+minute>=shamHour*60+shamMinute && hour*60+minute < kuptanHour*60+kuptanMinute){
							tablerow5.setBackgroundDrawable(getResources().getDrawable(R.drawable.namaz_line));
							}
						else if(hour*60+minute>=kuptanHour*60+kuptanMinute && hour*60+minute<23*60+60){
							tablerow6.setBackgroundDrawable(getResources().getDrawable(R.drawable.namaz_line));
							}
						else {
							tablerow1.setBackgroundDrawable(getResources().getDrawable(R.drawable.namaz_line));
							}
						}
			  }
	}
		 @Override
		    public boolean onCreateOptionsMenu(Menu menu)
		    {
			 menu.add(Menu.NONE, MENU_FAQ, Menu.NONE,
		             "").setIcon(R.drawable.settingsbutton);
		    menu.add(Menu.NONE, MENU_ABOUT, Menu.NONE,
		             "").setIcon(R.drawable.infobutton);
		     return true;
		    }
		 @Override
		    public boolean onOptionsItemSelected(MenuItem item)
		    {
		    
			 switch (item.getItemId()) {
		      case MENU_FAQ:
		        startActivity(new Intent(this,Settings.class));
		        return true;
		      case MENU_ABOUT:
		        return true;
		      default:
		        return false;
		    }
		 
		    
}
		 
		 
		
		
		    
}